var cfg = require('../../utils/cfg');
// var socketUtil = require('../../utils/socketUtil');


var app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    joinCount: 0,
    timeWaitFun: {},
    count: 0,
    waitPic: '/images/wait1.png',
    waitText: '等待对方...',
    score: 0,
    moqi: 0,
    moqiScore: 0,
    userAva: '',
    userText: '',
    otherUser: {},
    paperId: '',
    model: 0,
    finishUsers : [],
    tacitAvg : '',
    reward : '',
    hiddenmodalput: true,
    zsjifen: 0,
    pkOpenId : ''
  },

  waitUser: function () {
    let that = this;
    that.data.timeWaitFun = setInterval(function () {
      console.log('>>>>>wait...' + that.data.count);
      let waitPic = that.data.count % 2 == 0 ? '/images/wait1.png' : '/images/wait2.png';
      let waitText = that.data.count % 2 == 0 ? '等待对方...' : '等待对方. .';
      that.data.count += 1;
      that.setData({ waitPic: waitPic });
      that.setData({ waitText: waitText });
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _self = this;


    let paperId = options.paperId;
    _self.data.model = options.model;

    console.log('试卷ID=' + paperId);

    _self.setData({
      userInfo: app.globalData.userInfo,
      paperId: paperId
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.waitUser();
    //发送完成请求
    this.finishAnswer();
  },

  finishAnswer: function () {
    let that = this;
    wx.request({
      url: cfg.host + cfg.mwurl.finishAnswer,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket'),
        model: 0,
        paperId: that.data.paperId
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.code !== 1000) {
          return;
        }

        let userInfo = res.data.data;
        if (!userInfo || userInfo.length <= 0) {
          return;
        }

        let finishUsers = that.data.finishUsers;
        for (let i=0;i<userInfo.length; i++) {
          finishUsers.push(userInfo[i]);
        }

        that.setData({ finishUsers: finishUsers });

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })

    app.finishMic();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //注册回调函数
    // socketUtil.registCallBack(this.doSocket);
    app.globalData.socketCallBack = this.doSocket;
  },

  /**
   * 计算团队默契分
   */
  answerGroupTacit : function() {
    let that = this;
    let paperData = wx.getStorageSync('paperInfo');

    // let paperInfo = paperData.data.paper;
    // let playNum = paperData.data.playNum;
    // let roomTicket = paperData.data.roomTicket;
    // let openId = paperData.data.openId;

    wx.request({
      url: cfg.host + cfg.mwurl.answerGroupTacit,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket'),
        playNum: paperData.data.playNum,
        paperId: that.data.paperId
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.code !== 1000) {
          return;
        }
        
        let tacitAvg = res.data.data.tacitAvg;
        let reward = res.data.data.reward;

        clearInterval(that.data.timeWaitFun);

        wx.showToast({
          title: '团队默契度' + tacitAvg + '%, 默契分' + reward,
          icon: 'none',
          duration: 2000
        })

        that.setData({ waitPic: '/images/score.png', waitText: '默契度' + tacitAvg + '%, 默契分' + reward });

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  doSocket: function (res) {
    console.log('ready socket ' + res);
    let that = this;
    let wsDTO = res

    if (1005 === wsDTO.wsType) {
      
      console.log(">>>所有人答题完毕");
      //计算默契分
      that.answerGroupTacit();
    }

    if (1003 === wsDTO.wsType) {

      let userInfo = wsDTO.data;

      let finishUsers = that.data.finishUsers;
      finishUsers.push(userInfo);
      
      that.setData({finishUsers: finishUsers });

    }

  },

  toNextPlay: function () {
    wx.request({
      url: cfg.host + cfg.mwurl.nextPlay,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket'),
        model: 0
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.code !== 1000) {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
          return;
        }

        //进入下一轮
        wx.reLaunch({
          url: '/pages/moreReady/moreReady'
        })

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  nextPlay: function () {
    let that = this;

    if (that.data.finishUsers.length <= 0) {
      wx.showModal({
        title: '提示',
        content: '确定进行下一轮？',
        success: function (res) {
          if (res.confirm) {
            that.toNextPlay();
          } else if (res.cancel) {

          }
        }
      })
    } else {
      that.toNextPlay();
    }


  },

  tacitScore: function () {
    let that = this;
    
  },

  leaveRoom: function () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定离开房间？',
      success: function (res) {
        if (res.confirm) {
          //离开房间进入首页
          wx.request({
            url: cfg.host + cfg.mwurl.delRoom,
            data: {
              openId: wx.getStorageSync('loginUser').openId,
              roomTicket: wx.getStorageSync('roomTicket')
            },
            success: function (res) {
              wx.reLaunch({
                url: '/pages/home/home'
              })
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            method: 'POST'
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  leaveAnswer: function () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '进入下一个问卷调查？',
      success: function (res) {
        if (res.confirm) {
          //进入下一轮
          that.nextPlay();
          wx.reLaunch({
            url: '/pages/ready/ready'
          })
        } else if (res.cancel) {
          //进入首页
          wx.reLaunch({
            url: '/pages/home/home'
          })
        }
      }
    })
  },

  lookDetail : function(event){
    let that = this;
    wx.showModal({
      title: '提示',
      cancelText : '赠送积分',
      confirmText : '默契度',
      content: '',
      success: function (res) {
        if (res.confirm) {
          that.pkTacit(event);
        } else if (res.cancel) {
          //TODO 弹出赠送框
          let pkOpenId = event.currentTarget.dataset.userOpenId;
          that.data.pkOpenId = pkOpenId;
          that.modalinput();
        }
      }
    })
  },

  modalinput: function () {
    let that = this;

    that.setData({
      hiddenmodalput: !that.data.hiddenmodalput
    })
  },

  jifenzhi: function (e) {
    let that = this;
    that.setData({ zsjifen: e.detail.value });
    console.log('>>>>送积分了' + e.detail.value);
  },

  //直接赠送
  sjCancel: function () {
    let that = this;
    that.setData({
      hiddenmodalput: true
    })

    if (that.data.zsjifen == '' || that.data.zsjifen <= 0) {
      return;
    }

    wx.request({
      url: cfg.host + cfg.mwurl.zjzengsong,
      data: {
        openId: that.data.pkOpenId,
        giveOpenId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket'),
        integral: that.data.zsjifen
      },
      success: function (res) {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  //索要
  sjConfirm: function () {
    console.log('>>>>索要分了');
    let that = this;

    that.setData({
      hiddenmodalput: true
    })

    if (that.data.zsjifen == '' || that.data.zsjifen <= 0) {
      return;
    }

    wx.request({
      url: cfg.host + cfg.mwurl.zengsong,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        giveOpenId: that.data.pkOpenId,
        roomTicket: wx.getStorageSync('roomTicket'),
        integral: that.data.zsjifen,
        accept: true
      },
      success: function (res) {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  pkTacit:function(event) {
    let that = this;

    let pkOpenId = event.currentTarget.dataset.userOpenId;
    console.log(">>>>>>>PK" + pkOpenId);
    
    let paperData = wx.getStorageSync('paperInfo');

    // let paperInfo = paperData.data.paper;
    // let playNum = paperData.data.playNum;
    // let roomTicket = paperData.data.roomTicket;
    // let openId = paperData.data.openId;

    wx.request({
      url: cfg.host + cfg.mwurl.answerPointTacit,
      data: {
        currentOpenId: wx.getStorageSync('loginUser').openId,
        openId: pkOpenId,
        roomTicket: wx.getStorageSync('roomTicket'),
        model: 1,
        playNum: paperData.data.playNum
      },
      success: function (res) {
        clearInterval(that.data.timeWaitFun);
        console.log('>>>>默契分比' + res.data.data);
        if (res.data.code !== 1000) {
          return;
        }
        
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '你俩的默契度' + res.data.data.tacitAvg + '%，默契分' + res.data.data.reward,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('ready onUnload');
    clearInterval(this.data.timeWaitFun);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})